import json
import datetime
import matplotlib.pyplot as plt
import time
import numpy as np


def main(range_day):
    path1 = '/show/WDN/misc/dept/lgt/RenderFarm/archive/Classification_report/daily_report/data_json/'
    path2 = '/show/WDN/misc/dept/lgt/RenderFarm/archive/Classification_report/daily_report/week_pic/'
    name = '_type_submit.json'

    # method to get the json content
    def get_date_json(date_name):
        filename = path1+'%s_machine_usage.json'%date_name
        with open(filename) as f:
            data = json.load(f)
        return data

    # get the data time in list
    date_time_7 = []
    data_now = datetime.datetime.now().strftime("%Y-%m-%d")
    # range_day = 7
    for i in range(range_day+1):
        # print i
        data_week_ago = (datetime.datetime.now() + datetime.timedelta(days=-(range_day-i))).strftime("%Y-%m-%d")
        date_time_7.append(data_week_ago)
    print date_time_7

    # to make a big dict to
    dict_week_date = {}
    for i in date_time_7:
        dict_week_date[i] = get_date_json(i)

    # from now to 7 day before
    dict_show_merge = {'All_run':[],'MR':[],'Katana':[], 'BJ':[],'Time':[]}
    for i in date_time_7:
        for key, value in dict_week_date[i].items():
            dict_show_merge[key] += value

    # for i in dict_show_merge.items():
    #     print i

    all_run = dict_show_merge['All_run'][15:]
    Katana = dict_show_merge['Katana'][15:]
    MR = dict_show_merge['MR'][15:]
    Time = dict_show_merge['Time'][15:]
    a = list(xrange(0, len(all_run)))
    fig = plt.figure()
    fig.set_size_inches(16, 9, forward=True)
    ax = fig.add_subplot(1, 1, 1)
    major_ticks = np.arange(0, len(Time), 24)
    minor_ticks = np.arange(0, len(Time), 24)

    x_sticks = []
    for i,j in enumerate(major_ticks):
        x_sticks.append(date_time_7[i][5:])
    # print np.array(x_sticks)
    y_sticks = np.arange(0, max(all_run)+100, 50)
    # print max(all_run)

    plt.plot(a, all_run,  ms=8, label=u'Run', color='green')
    plt.plot(a, Katana,  ms=8, label=u'Ka', color='red')
    plt.plot(a, MR,  ms=8, label=u'MR', color='blue')
    plt.xticks(a, np.array(x_sticks), fontsize='small')
    plt.xlabel("Time(Date)")
    plt.ylim(ymax=max(all_run) + 100)
    ax.set_xticks(major_ticks)
    ax.set_xticks(minor_ticks, minor=True)
    ax.set_yticks(y_sticks)
    ax.set_yticks(minor_ticks, minor=True)
    ax.grid(which='both')

    legend = plt.legend()
    frame = legend.get_frame()
    label_set_text = legend.get_texts()
    plt.setp(label_set_text, fontsize='small')
    frame.set_alpha(0.3)
    frame.set_facecolor('powderblue')
    plt.ylabel('machine_number')
    plt.title("Machine_Usage[%s 00:00am - %s 8:00am]" % (date_time_7[0], data_now))
    plt.savefig(path2+"Machine_Usage[%s].jpg" % (data_now[5:]))
    print 'pic_ok'

if __name__ == "__main__":
    current_time = time.localtime(time.time())
    print current_time
    main(7)  # 5days